import axios from './service';
import domain from './domain';
import url from './url';
// import apiSign from '@ebag/websign'; // TODO: 需要安装 @ebag/websign 包或提供替代方案
// 临时实现：如果 @ebag/websign 不可用，返回空字符串（实际项目中需要安装正确的包）
const apiSign = {
  sign: (params) => {
    // TODO: 实际项目中需要安装 @ebag/websign 包
    // 这里返回空字符串作为临时方案，可能需要根据实际签名逻辑调整
    console.warn('apiSign.sign is using temporary implementation, please install @ebag/websign package');
    return '';
  }
};
import { userType } from '@/utils/constant';
import store from '@/store';
import qs from 'qs';
/*
 * F_usertype:6 是这个项目需要传的,表示是精准教学管理平台的请求
 * 登录后获取的
 *  sessionId 对应 F_token (统一使用F_token，放在header中)
 *  userId 对应 F_admin_id (放在header中)
 *  传给后端做接口的验证
 */

const isTestHost = (host) => {
  return host.includes('test');
};

const EXAM_API_DOMAIN = domain.EXAM_API_DOMAIN;

const configFile = {
  headers: {
    'Content-Type': 'multipart/form-data',
  },
};

const ADMIN_STATIC_TOKEN = 'ny7FBMfXFtJgYdOVeUcsgA2twLBhpGQo'

function getFormData(obj) {
  const formData = new FormData();
  for(let [k,v] of Object.entries(obj)) {
    formData.append(k, v);
  }
  return formData;
}

function getAccessInfo() {
  return {
    userId: store.getters['user/userId'],
    sessionId: store.getters['user/sessionId'],
  };
}

function addAccessInfo(params = {}) {
  const tokenInfo = getAccessInfo();
  // 检查 token 是否存在，如果不存在则提示
  if (!tokenInfo.sessionId || !tokenInfo.userId) {
    console.warn('认证信息缺失，可能导致请求失败', tokenInfo);
  }
  // 统一使用F_token，不再使用F_accesstoken和token
  // token和用户信息都放在header中，不再放在params中
  params.F_usertype = userType;
  params.F_sign = apiSign.sign(params);
  return params;
}

function addStaticAccessInfo(params = {}) {
  const tokenInfo = getAccessInfo();
  params.F_accesstoken = ADMIN_STATIC_TOKEN;
  params.F_user_id = tokenInfo.userId;
  params.F_admin_id = tokenInfo.userId;
  params.F_usertype = userType;
  return params
}

function appendAccessInfo(formData) {
  const tokenInfo = getAccessInfo();
  // 统一使用F_token，不再使用F_accesstoken和token
  // token和用户信息都放在header中，不再放在formData中
  formData.append('F_usertype', userType);
  return formData;
}

function get(url, params = {}) {
  return axios.get(url, { params });
}

function getBlob(url, params = {}) {
  params = addAccessInfo(params);
  return axios.get(url, {
    params,
    responseType: 'blob',
  });
}

function getBlobByPost(url, formData) {
  formData = appendAccessInfo(formData);
  return axios.post(url, formData, { responseType: 'blob'});
}

function post(url, formData) {
  return axios.post(url, formData, configFile);
}

function getWithAccess(url, params = {}) {
  params = addAccessInfo(params);
  return axios.get(url, { params });
}

function getWithStaticAccess(url, params = {}) {
  params = addStaticAccessInfo(params);
  return axios.get(url, { params });
}

function jsonPost(url, params = {}) {
  // params = addAccessInfo(params);
  return axios.post(url, qs.stringify(params), {
    headers: {
      'Content-Type': 'application/json; charset=utf-8',
    },
  });
}

function postWithAccess(url, formData) {
  formData = appendAccessInfo(formData);
  return axios.post(url, formData, configFile);
}

function putWithAccess(url, formData) {
  formData = appendAccessInfo(formData);
  return axios.put(url, formData, configFile);
}

function deleteWithAccess(url, params) {
  params = addAccessInfo(params);
  return axios.delete(url, {
    params,
  });
}

const api = {
  sendPhoneCode(formData) {
    return post(url.SENDCODE, formData);
  },
  login(formData) {
    formData.append('userType', userType);
    return post(url.LOGIN, formData);
  },
  getDistricts(params) {
    return getWithAccess(url.DISTRICTS, params);
  },
  getDistricts2(params) {
    const tokenInfo = getAccessInfo();
    params.F_user_id = tokenInfo.userId;
    return getWithAccess(url.DISTRICTS2, params);
  },

  /***** 权限管理相关的 api *****/
  // 角色相关 api
  getRoles(params) {
    return getWithAccess(url.ROLES, params);
  },
  // 已废弃：改用 getSystemRoles() 或 getNonSchoolRoles() 接口
  // getSysRoles(params) {
  //   return getWithAccess(url.SYSROLES, params);
  // },
  // 获取系统角色列表（rb_system_role表）
  getSystemRoles(params) {
    return getWithAccess(url.SYSTEM_ROLE_LIST, params);
  },
  // 分页获取系统角色列表（支持权限过滤）
  getSystemRolesWithPagination(params) {
    return getWithAccess(url.SYSTEM_ROLE_PAGE, params);
  },
  // 创建系统角色（rb_system_role表）
  createSystemRole(params) {
    return postWithAccess(url.SYSTEM_ROLE_CREATE, getFormData(params));
  },
  // 更新系统角色（rb_system_role表）
  updateSystemRole(params) {
    return putWithAccess(url.SYSTEM_ROLE_UPDATE, getFormData(params));
  },
  // 删除系统角色（rb_system_role表）
  deleteSystemRole(params) {
    return deleteWithAccess(url.SYSTEM_ROLE_DELETE, params);
  },
  // 获取所有非学校角色列表（F_is_school_role=0）
  getNonSchoolRoles(params) {
    return getWithAccess(url.SYSTEM_ROLE_NON_SCHOOL, params);
  },
  // 获取所有学校角色列表（F_is_school_role=1）
  getSchoolRoles(params) {
    return getWithAccess(url.SYSTEM_ROLE_SCHOOL, params);
  },
  addRole(formData) {
    return postWithAccess(url.ROLE, formData);
  },
  deleteRole(params) {
    return deleteWithAccess(url.DELETEROLE, params);
  },
  disableRole(formData) {
    return putWithAccess(url.DISABLEROLE, formData);
  },

  // 成员相关 api
  getUserInfo(params) {
    return getWithAccess(url.USERINFO, params);
  },
  getPermission(params) {
    return getWithAccess(url.GET_USER_PERMISSION2, params);
  },
  getUsers(params) {
    return getWithAccess(url.USERS, params);
  },
  addUser(formData) {
    return postWithAccess(url.USER, formData);
  },
  // 创建或更新用户（新接口，使用rb_user和rb_user_role表）
  createOrUpdateUser(params, isUpdate = false) {
    console.log('API: createOrUpdateUser 被调用', {
      url: url.USER_CREATE_UPDATE,
      method: isUpdate ? 'PUT' : 'POST',
      params: params
    });
    const method = isUpdate ? putWithAccess : postWithAccess;
    return method(url.USER_CREATE_UPDATE, getFormData(params));
  },
  // deleteUser(params) {
  //   return deleteWithAccess(url.DELETEUSER, params);
  // },
  deleteUserNew(params) {
    return deleteWithAccess(url.DELETEUSER_NEW, params);
  },
  disableUser(formData) {
    return putWithAccess(url.DISABLEUSER, formData);
  },
  /***** 权限管理相关的 api 完 *****/
  //更改学校名称
  updateSchoolName(params){
    return axios.post(url.UPDATE_SCHOOL_NAME, params);
  },

  getSchools(params) {
    return getWithAccess(url.SCHOOLS, params);
  },
  getSchoolsByIds(params) {
    return getWithAccess(url.SCHOOLSBYIDS, params);
  },
  getSChoolsByAdmin(params) {
    const tokenInfo = getAccessInfo();
    params.F_user_id = tokenInfo.userId;
    return getWithAccess(url.SCHOOLSBYADMIN, params);
  },
  getDistrictSchools(params) {
    return getWithAccess(url.DISTRICTSCHOOLS, params);
  },
  getSchool(params) {
    return getWithAccess(url.SCHOOL, params);
  },
  getOptions(params) {
    return getWithAccess(url.OPTIONS, params);
  },

  /*** 学生相关的 api ***/
  getStudents(params) {
    return getWithAccess(url.STUDENTS, params);
  },
  getAStudent(params) {
    return getWithAccess(url.STUDENT, params);
  },
  updateStudent(formData) {
    return putWithAccess(url.STUDENT, formData);
  },
  deleteStudent(params) {
    return deleteWithAccess(url.STUDENT, params);
  },
  clearStudents(params) {
    return deleteWithAccess(url.CLEARSTUDENT, params);
  },
  addStudent(formData) {
    return postWithAccess(url.STUDENT, formData);
  },
  getTeachers(params) {
    return getWithAccess(url.TEACHERS, params);
  },
  getTeacher(params) {
    return getWithAccess(url.TEACHER, params);
  },
  updateTeacher(params) {
    return putWithAccess(url.TEACHER, params);
  },
  deleteTeacher(params) {
    return deleteWithAccess(url.TEACHER, params);
  },
  clearTeachers(params) {
    return deleteWithAccess(url.CLEARTEACHER, params);
  },
  getClasses(params) {
    return getWithAccess(url.CLASSES, params);
  },
  getTeachInfoList(params) {
    return getWithAccess(url.TEACH_INFO, params);
  },
  updateClassTeachInfo(params) {
    const formData = getFormData(params);
    return putWithAccess(url.CLASS_TEACH_INFO, formData);
  },
  getSchoolClasses(params) {
    return getWithAccess(url.ALL_CLASSES, params);
  },
  addClass(params) {
    return postWithAccess(url.CLASS, params);
  },
  getClass(params) {
    return getWithAccess(url.CLASS, params);
  },
  editClass(params) {
    return putWithAccess(url.CLASS, params);
  },
  deleteClass(params) {
    return deleteWithAccess(url.CLASS, params);
  },
  getTerm(params) {
    return getWithAccess(url.TERM, params);
  },
  addTeacher(formData) {
    return postWithAccess(url.TEACHER, formData);
  },

  /** 导入、导出相关的 api */
  exportStudentId(params) {
    return getBlob(url.EXPORTSTUDENTID, params);
  },
  exportStudentAccount(params) {
    return getBlob(url.EXPORT_STUDENT, params);
  },
  exportSchoolData(params) {
    return getBlob(url.EXPORT, params);
  },
  exportTeacherAndStudents(params) {
    return getBlob(url.EXPORT_TEACHER_AND_STUDENTS, params);
  },
  exportSchoolStudent(params) {
    return getBlob(url.EXPORTSTUDENT, params);
  },
  exportSchoolTeacher(params) {
    return getBlob(url.EXPORTTEACHER, params);
  },
  importSchoolPreview(formData) {
    return postWithAccess(url.PREVIEWSCHOOL, formData);
  },
  importUserPreview(formData) {
    return postWithAccess(url.PREVIEW_USER, formData);
  },
  importUserConfirm(formData) {
    return postWithAccess(url.CONFIRM_USER, formData);
  },
  importStudentPreview(formData) {
    return postWithAccess(url.PREVIEWSTUDENT, formData);
  },
  importTeacherPreview(formData) {
    return postWithAccess(url.PREVIEWTEACHER, formData);
  },
  importSchoolConfirm(formData) {
    return postWithAccess(url.CONFIRMSCHOOL, formData);
  },
  importStudentConfirm(formData) {
    return postWithAccess(url.CONFIRMSTUDENT, formData);
  },
  importTeacherConfirm(formData) {
    return postWithAccess(url.CONFIRMTEACHER, formData);
  },
  updateStudentPreview(formData) {
    return postWithAccess(url.PREVIEW_UPDATE_STUDENT, formData);
  },
  updateStudentConfirm(formData) {
    return postWithAccess(url.CONFIRM_UPDATE_STUDENT, formData);
  },
  /** 导入、导出相关的 api 完 */

  // 更新密码
  editStudentPW(formData) {
    return putWithAccess(url.EDIT_STUDENT_PW, formData);
  },
  editTeacherPW(formData) {
    return putWithAccess(url.EDIT_TEACHER_PW, formData);
  },

  updateUserPwd(formData) {
    return putWithAccess(url.UPDATE_USER_PW, formData);
  },

  setAccount(formData) {
    return postWithAccess(url.ACCOUNT, formData);
  },

  getSchoolSubject(school_id) {
    const params = {};
    if(school_id) {
      params.school_id = school_id;
    }
    return getWithStaticAccess(url.SCHOOL_SUBJECT_LIST, params);
  },

  // 更新用户密码
  editUserPW(formData) {
    return putWithAccess(url.EDIT_USER_PWD, formData);
  },

  generateAccount(formData) {
    return postWithAccess(url.GENERATE_ACCOUNT, formData);
  },

  getTeachInfo(params) {
    return getWithAccess(url.USER_TEACH_INFO, params);
  },

  exportErrorExcel(url, params) {
    return getBlobByPost(url, params);
  },

  getUserByPhone(params) {
    return getWithAccess(url.GET_USER, params);
  },

  combineStudents(formData) {
    return postWithAccess(url.COMBINE_STUDENTS, formData)
  },

  importEditTable(formData) {
    return postWithAccess(url.UPLOAD_EXCEL, formData);
  },
  getUserDistrictList(params) {
    return getWithStaticAccess(url.USER_DISTRICT_LIST, params);
  },
  getUserSchoolList(params) {
    return getWithStaticAccess(url.USER_SCHOOL_LIST, params);
  },
  getSchoolMasterList(params) {
    return getWithAccess(url.SCHOOL_MASTER, params);
  },
  getSchoolMasterList2(params) {
    return getWithAccess(url.SCHOOL_MASTER2, params);
  },
  getSchoolUserList(params) {
    return getWithAccess(url.SCHOOL_USER_LIST, params);
  },
  updateRoleUserList(params) {
    const formData = getFormData(params);
    return postWithAccess(url.UPDATE_ROLE_USER, formData);
  },

  // 添加创建学校接口
  createSchool(params) {
    return postWithAccess(url.CREATE_SCHOOL, getFormData(params));
  },
  
  // 检查学校数据是否已初始化
  checkSchoolDataInit(params) {
    return getWithAccess(url.CHECKSCHOOLDATAINIT, params);
  },

  // 系统成员管理相关 api
  getSystemUsers(params) {
    return getWithAccess(url.SYS_USERS, params);
  },
  createSystemUser(formData) {
    return postWithAccess(url.SYS_USER, formData);
  },
  deleteSystemUser(params) {
    return deleteWithAccess(url.DELETE_SYSTEM_USER, params);
  },
  disableSystemUser(params) {
    return postWithAccess(url.DISABLE_SYSTEM_USER, getFormData(params));
  },
  
  // 高中升学相关接口
  gradeUpgrade(params) {
    return postWithAccess(url.GRADE_UPGRADE, getFormData(params));
  },
  
  // 菜单管理相关接口
  getMenuList(params) {
    return getWithAccess(url.MENU_LIST, params);
  },
  // 根据用户ID获取顶级菜单（parent_id=0，用于导航栏）
  getTopMenusByUserId(params) {
    return getWithAccess(url.MENU_TOP_BY_USER, params);
  },
  // 根据菜单ID获取子菜单和功能按钮
  getMenuChildren(params) {
    return getWithAccess(url.MENU_CHILDREN, params);
  },
  getAllMenus(params) {
    return getWithAccess(url.MENU_ALL, params);
  },
  // 根据用户ID获取所有菜单权限（包括所有按钮权限）
  getAllMenusByUserId(params) {
    return getWithAccess(url.MENU_ALL_BY_USER, params);
  },
  createMenu(params) {
    return postWithAccess(url.MENU, getFormData(params));
  },
  updateMenu(params) {
    return putWithAccess(url.MENU, getFormData(params));
  },
  deleteMenu(params) {
    return deleteWithAccess(url.MENU, params);
  },
  getMenuListByRole(params) {
    return getWithAccess(url.MENU_BY_ROLE, params);
  },
  setRoleMenu(params) {
    return postWithAccess(url.MENU_BY_ROLE, getFormData(params));
  },
  getRoleMenuIds(params) {
    return getWithAccess(url.MENU_ROLE_IDS, params);
  },
  // 获取系统角色（rb_system_role）已分配的菜单ID列表
  getSystemRoleMenuIds(params) {
    return getWithAccess(url.MENU_SYSTEM_ROLE_IDS, params);
  },
  // 设置系统角色（rb_system_role）菜单权限
  setSystemRoleMenu(params) {
    return postWithAccess(url.MENU_SYSTEM_ROLE, getFormData(params));
  },
};

export default api;
